<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\common\Auth;
use app\api\common\Base;
use app\api\exception\BaseException;
use app\api\model\UserInfo;
use app\api\validate\AccountScene;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Cache;
use think\facade\Db;

class Account extends BaseException
{

    /**
     * 不需要登录方法
     */
    protected $noAuth = ['login'];


    /**
     * 【ALL】
     * 所有人员登录
     * 下发菜单权限
     */


    public function login()
    {
        $request = Request::param();
        try {
            validate(AccountScene::class)
                ->scene('login')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }

        $userinfo = Db::name("account")->where(["username" => $request["username"], "data_state" => 1])->find();
        if ($userinfo) {
            if (strcmp(hashpassword($request["password"]), $userinfo["password"]) == 0) {
                //密码正确下发授权证书和生成Token
                $header = request()->header();
                $time = time();
                $sign = Auth::getSignkey(['did' => $header['did'], 'time' => $time, 'version' => $header['version'], 'ip' => request()->ip()]);
                $token = signToken($userinfo["user_id"], $userinfo);
                $data = [
                    'sign' => $sign,
                    'user_id' => $userinfo["user_id"],
                    'token' => $token,
                    'time' => $time,
                ];
                //将授权码存入数据库中
                $token_data = [
                    'token' => $token,
                    'sign' => $sign,
                    'user_id' => $userinfo["user_id"],
                    'ip' => request()->ip(),
                    'user_type' => $userinfo["user_type"],
                    'create_time' => date("Y-m-d H:i:s", time()),
                    'update_time' => date("Y-m-d H:i:s", time()),
                    'data_state' => 1
                ];
                $check = Db::name("permission")->insertGetId($token_data);
                if ($check) {
                    Cache::set('token' . getClientIp(), $sign, 3600 * 24 * 30);
                    Cache::set("token", $token, 3600 * 24 * 30);
                    $time = time();
                    $realAddress = getIpAddress(getClientIp());

                    $loginlog = [
                        "user_id" => intval($userinfo["user_id"]),
                        "username" => $userinfo["username"],
                        "ip" => getClientIp(),
                        "user_type" => intval($userinfo["user_type"]),
                        "real_address" => empty($realAddress) ? "暂未获取" : $realAddress,
                        "create_time" => date("Y-m-d H:i:s", time())
                    ];

                    Db::name("login_log")->insert($loginlog);
                    $update = [
                        "last_login_time" => date("Y-m-d H:i:s", time()),
                        "last_login_ip" => getClientIp()
                    ];
                    Db::name("account")->where(["user_id" => $userinfo["user_id"]])->update($update);
                    Cache::set($time . 'token' . request()->ip(), $sign, 3600 * 24 * 30);
                    Cache::set($sign, $this->user_id, 3600 * 24 * 30);
                    return self::Success($data, '登陆成功', 200);
                } else {
                    return self::Error(null, '系统繁忙，请稍后再试', 500);
                }
            } else {
                return self::Error(null, '密码错误', 10002);
            }
        } else {
            return self::Error(null, '账号不存在或已加入黑名单，请联系上级主管', 10002);
        }
    }

    /**
     * @return \think\Response|void
     * 超级管理员添加管理员 、 财务
     * 管理员添加财务、用户
     *
     */
    public function register()
    {

        $request = Request::param();

        try {
            validate(AccountScene::class)
                ->scene('register')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if ($request["user_type"] == 2) {
            if ($this->user_type > 1) {
                return self::Error(null, "无权限", 10002);
            }
        }
        if ($request["user_type"] == 3) {
            if ($this->user_type > 2) {
                return self::Error(null, "无权限", 10002);
            }
        }
        if ($request["user_type"] == 4) {
            if ($this->user_type > 2) {
                return self::Error(null, "无权限", 10002);
            }
        }
        if ($this->user_type >= 3) {
            return self::Error(null, "无权限", 10002);
        }
        $checkUserClass = Db::name("account_position")->where(["class_id" => $request["group_id"], "id" => $request["position"]])->find();
        if (!$checkUserClass) {
            return self::Error(null, "当前所选分类和职位不存在", 10002);
        }
        $insertdata = [
            "username" => $request["username"],
            "avatar_url" => empty($request["avatar_url"]) ? '/static/images/avatar_url.png' : $request["avatar_url"],
            "password" => hashpassword($request["password"]),
            "telephone" => $request["telephone"],
            "user_type" => intval($request["user_type"]),
            "real_name" => empty($request["real_name"]) ? "匿名用户" : $request["real_name"],
            "is_main" => isset($request["is_main"]) ? $request["is_main"] : 0,
            "server_rate" => isset($request["server_rate"]) ? $request["server_rate"] : 0,
            "group_id" => intval($request["group_id"]),
            "position" => intval($request["position"]),
            "data_state" => 1,
            "create_time" => date("Y-m-d H:i:s", time()),
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $id = Db::name("account")->insertGetId($insertdata);
        Db::name("account")->where(["id" => $id])->update(["user_id" => $id]);
        if ($id) {
            return self::Success(null, '注册成功', 200);
        } else {
            return self::Error(null, "注册失败", 10002);
        }

    }

    /**
     * 【超级管理员、管理员】
     * 假删除
     * 数据筛选 姓名 手机号 身份下拉筛选 分类下拉筛选
     * 获取全部用户列表
     */
    public function getUserInfoList()
    {
        $data = Request::param();
        if ($this->user_id > 2) {
            return self::Error(null, "当前账号无查看用户信息权限", 10002);
        }
        $fieldStr = "id,user_id,username,telephone,avatar_url,user_type,real_name,is_main,server_rate,group_id,position,data_state,create_time,last_login_time,last_login_ip";

        $search = [
            ["user_id", "<>", $this->user_id],
            ["user_type", ">", $this->user_type]
        ];
        $order = ["id" => "asc"];
        if ($data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }
//        if ()
//        $order=
        /**
         * 单一模糊查询开始
         */
        //姓名模糊查询
        if (isset($data["username"]) && !empty($data["username"])) {
            $search[] = ["username", "like", "%" . $data["username"] . "%"];
        }
        //电话模糊查询
        if (isset($data["telephone"]) && !empty($data["telephone"])) {
            $search[] = ["telephone", "like", "%" . $data["telephone"] . "%"];
        }
        //真实姓名模糊查询
        if (isset($data["real_name"]) && !empty($data["real_name"])) {
            $search[] = ["real_name", "like", "%" . $data["real_name"] . "%"];
        }
        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        //用户类型筛选查询
        if (isset($data["user_type"]) && $data["user_type"] != '') {
            array_push($search, ["user_type", "=", $data["user_type"]]);
        }
        //是否为主号筛选查询
        if (isset($data["is_main"]) && $data["is_main"] != '') {
            array_push($search, ["is_main", "=", $data["is_main"]]);
        }
        //组别筛选查询
        if (isset($data["class_id"]) && $data["class_id"] != '') {
            array_push($search, ["group_id", "=", $data["class_id"]]);
        }
        //职位筛选查询
        if (isset($data["position"]) && $data["position"] != '') {
            array_push($search, ["position", "=", $data["position"]]);
        }

        $userlist = Db::name("account")->where($search)->field($fieldStr)->order($order)->page($data["page"], $data["limit"])->select()->toArray();
        $count = Db::name("account")->where($search)->count();
        foreach ($userlist as $key => $value) {
            $userlist[$key]["avatar_url"] = "http://" . $_SERVER['HTTP_HOST'] . $value["avatar_url"];
            $userlist[$key]["group_id"] = Db::name("account_class")->where(["id" => $value["group_id"]])->field("id,name")->find();
            $userlist[$key]["position"] = Db::name("account_position")->where(["id" => $value["position"]])->field("id,name")->find();
        }
        $userTypeList = [];
        switch ($this->user_type) {
            case 1:
                $userTypeList = [
                    ["id" => 2, "name" => "管理员"],
                    ["id" => 3, "name" => "财务"],
                    ["id" => 4, "name" => "仓库"],
                    ["id" => 5, "name" => "售后"],
                    ["id" => 6, "name" => "员工"],
                ];
                break;
            case 2:
                $userTypeList = [
                    ["id" => 3, "name" => "财务"],
                    ["id" => 4, "name" => "仓库"],
                    ["id" => 5, "name" => "售后"],
                    ["id" => 6, "name" => "员工"],
                ];
                break;
        }
        $list = [
            "total" => $count,
            "page" => $data["page"],
            "limit" => $data["limit"],
            "list" => $userlist,
            "userTypeList" => $userTypeList
        ];
        //Db::name("account")->getLastSql();
        return self::Success($list, '获取成功', 200);
    }

    /**
     * 【超级管理员、管理员】
     * 数据假删除 1为正常 0为删除
     * 可以通过下拉方式调取已经删除的用户数据
     * 更改data_state字段状态
     */
    public function updateUserState()
    {
        $request = Request::param();
        try {
            validate(AccountScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updatedata = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("account")->where(["user_id" => $request["user_id"]])->find();
        if ($check) {
            $result = Db::name("account")->where(["user_id" => $request["user_id"]])->update($updatedata);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '用户不存在', 10002);
        }

    }

    /**
     * 【超级管理员、管理员】
     * 管理员更新用户数据
     * 更改账号 手机 身份 分类 是否为主号 费率
     */
    public function updateUserInfo()
    {
        $request = Request::param();
        try {
            validate(AccountScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $check = Db::name("account")->where(["user_id" => $request["user_id"]])->find();
        if ($check) {
            $update = [
                "username" => $request["username"],
                "telephone" => $request["telephone"],
                "user_type" => $request["user_type"],
                "real_name" => empty($request["real_name"]) ? "匿名用户" : $request["real_name"],
                "is_main" => $request["is_main"],
                "server_rate" => $request["server_rate"],
                "group_id" => $request["group_id"],
                "position" => $request["position"],
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
            $result = Db::name("account")->where(["user_id" => $request["user_id"]])->update($update);
            if ($result) {
                return self::Success(null, '修改成功', 200);
            } else {
                return self::Error(null, '修改失败', 10002);
            }
        } else {
            return self::Error(null, '用户不存在', 10002);
        }


    }

    /**
     * 【超级管理员、管理员】
     * 管理员更新用户密码
     * 目前为直接重置，建议改为手动输入
     */
    public function updateUserPassword()
    {
        $request = Request::param();
        try {
            validate(AccountScene::class)
                ->scene('adminchange_password')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if (strcmp($request["password"], $request["re_password"]) == 0) {
            $updateData = [
                "password" => hashpassword($request["password"]),
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
            $result = Db::name("account")->where(["data_state" => 1, "user_id" => $request["user_id"]])->update($updateData);
            if ($result) {
                return self::Success(null, '修改成功', 200);
            } else {
                return self::Error(null, '修改失败', 10002);
            }
        } else {
            return self::Error(null, "两次输入的密码不一致", 10002);
        }
    }

    /**
     * 【ALL】
     * 所有用户可以更新自己的密码
     */
    public function changeUserPassword()
    {
        $request = Request::param();
        try {
            validate(AccountScene::class)
                ->scene('change_password')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if (strcmp($request["password"], $request["re_password"]) == 0) {
            $updateData = [
                "password" => hashpassword($request["password"]),
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
            $result = Db::name("account")->where(["data_state" => 1, "user_id" => $this->user_id])->update($updateData);
            if ($result) {
                return self::Success(null, '修改成功', 200);
            } else {
                return self::Error(null, '修改失败', 10002);
            }
        } else {
            return self::Error(null, "两次输入的密码不一致", 10002);
        }
    }


    public function getUserInfo()
    {
        $fieldStr = "id,user_id,username,telephone,avatar_url,user_type,real_name,is_main,server_rate,group_id,position,data_state,create_time,last_login_time,last_login_ip";
        $userinfo = Db::name("account")->where(["user_id" => $this->user_id])->field($fieldStr)->find();
        // $routers = Db::name("routers")->where(["user_type" => $this->user_id])->field("name,router")->select();
        $routers = [];
        if ($userinfo["user_type"] == 1) {
            $routers = ['root', "admin", "finance", 'user'];

        }
        if ($userinfo["user_type"] == 2) {
            $routers = ["admin", "finance", 'user'];
        }
        if ($userinfo["user_type"] == 3) {
            $routers = ["finance"];
        }
        if ($userinfo["user_type"] >= 4) {
            $routers = '[user]';
        }
        $userinfo["avatar_url"] = "http://" . $_SERVER['HTTP_HOST'] . $userinfo["avatar_url"];
        $data = [
            "userinfo" => $userinfo,
            "roles" => $routers,
            "menu" => $this->getRouterList($userinfo["user_type"])
        ];
        return self::Success($data, '获取成功', 200);
    }


    //获取路由权限
    public function getRouterList($user_type)
    {
        $fieldStr = "id,pid,name,icon,children_path,path,component_two,user_type,title,redirect,component,alwaysShow,hidden,noCache,activeMenu,type,sort";

        if ($user_type == 1) {
            $parentlist = Db::name("routers")->where(["pid" => 0, "data_state" => 1])->field($fieldStr)->order("sort desc")->select()->toArray();
            $parentlist = $this->refData($parentlist,$fieldStr,$user_type);
        }

        if ($user_type == 2) {
            $where = [
                ["pid",'=',0],
                ["user_type", '>', 1],
                ["data_state", '=', 1]
            ];
            $parentlist = Db::name("routers")->where($where)->field($fieldStr)->select()->toArray();
            $parentlist = $this->refData($parentlist,$fieldStr,$user_type);
        }
        if ($user_type == 3) {
            $where = [
                ["pid",'=',0],
                ["user_type", '>', 2],
                ["data_state", '=', 1]
            ];
            $parentlist = Db::name("routers")->where($where)->field($fieldStr)->select()->toArray();
            $parentlist = $this->refData($parentlist,$fieldStr,$user_type);
        }
        if ($user_type >= 4) {
            $where = [
                ["pid",'=',0],
                ["user_type", '>=', 4],
                ["data_state", '=', 1]
            ];
            $parentlist = Db::name("routers")->where($where)->field($fieldStr)->select()->toArray();
            $parentlist = $this->refData($parentlist,$fieldStr,$user_type);
        }

        return $parentlist;
    }

    public function refData($parentlist,$fieldStr,$user_type){
        foreach ($parentlist as $key => $value) {
            if ($user_type == 1){
                $where = [
                    ["pid" ,'=', $value["id"]],
                    ["data_state" ,'=', 1]
                ];
            }
            if ($user_type == 2){
                $where = [
                    ["pid" ,'=', $value["id"]],
                    ["data_state" ,'=', 1],
                    ["user_type" ,'>=',2]
                ];
            }
            if ($user_type == 3){
                $where = [
                    ["pid" ,'=', $value["id"]],
                    ["data_state" ,'=', 1],
                    ["user_type" ,'>=',3],
                    ["no_user_type","<>",3]
                ];
            }
            if ($user_type >= 4){
                $where = [
                    ["pid" ,'=', $value["id"]],
                    ["data_state" ,'=', 1],
                    ["user_type" ,'>=',4]
                ];
            }
            $children = Db::name("routers")->where($where)->order("sort desc")->field($fieldStr)->select();
            if (count($children) != 0){
                $parentlist[$key]["children"] = $children;
                $parentlist[$key]["alwaysShow"] = $parentlist[$key]["alwaysShow"] == 1 ? true : false;
                $parentlist[$key]["hidden"] = $parentlist[$key]["hidden"] == 1 ? true : false;
                $parentlist[$key]["noCache"] = $parentlist[$key]["noCache"] == 1 ? true : false;
            }else{
                $arr =[];
                $parentlist[$key]["alwaysShow"] = $parentlist[$key]["alwaysShow"] == 1 ? true : false;
                $parentlist[$key]["hidden"] = $parentlist[$key]["hidden"] == 1 ? true : false;
                $parentlist[$key]["noCache"] = $parentlist[$key]["noCache"] == 1 ? true : false;
                $parentlist[$key]["activeMenu"] = $parentlist[$key]["activeMenu"] == 1 ? true : false;
                $value["component"] = $value["component_two"];
                $value["path"] = $value["children_path"];
                unset($parentlist[$key]["name"]);
                unset($parentlist[$key]["icon"]);
                unset($value["component_two"]);
                unset($parentlist[$key]["component_two"]);
                unset($value["children_path"]);
                unset($parentlist[$key]["children_path"]);
                array_push($arr,$value);
                $parentlist[$key]["children"] = $arr;
            }

        }
        return $parentlist;
    }


    public function getUserProfileInfo(){
        $fieldStr = "id,user_id,username,telephone,avatar_url,user_type,real_name,is_main,server_rate,group_id,position,data_state,create_time,last_login_time,last_login_ip";
        $userinfo = Db::name("account")->where(["user_id" => $this->user_id])->field($fieldStr)->find();
        $userinfo["avatar_url_s"] = $userinfo["avatar_url"];
        $userinfo["avatar_url"] = "http://" . $_SERVER['HTTP_HOST'] . $userinfo["avatar_url"];


        return self::Success($userinfo, '获取成功', 200);
    }


    public function updateUserProfileInfo(){
        $request = Request::param();
        $updateData = [];
        try {
            validate(AccountScene::class)
                ->scene('change_user')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if (empty($request['password'])){
            $updateData = [
                "real_name" => $request["real_name"],
                "telephone" => $request["telephone"],
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
        }else{
            if (strcmp($request["password"], $request["re_password"]) == 0) {
                $updateData = [
                    "password" => hashpassword($request["password"]),
                    "real_name" => $request["real_name"],
                    "telephone" => $request["telephone"],
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
            } else {
                return self::Error(null, "两次输入的密码不一致", 10002);
            }
        }
        $result = Db::name("account")->where(["data_state" => 1, "user_id" => $this->user_id])->update($updateData);
        if ($result) {
            return self::Success(null, '修改成功', 200);
        } else {
            return self::Error(null, '修改失败', 10002);
        }
    }
}